package com.zy.aop.excerse1;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;

/**
 * Created by zy on 2015/11/29.
 */
public class BoundedHashSet<T> {
    private final Set<T> set;
    private final Semaphore sem;

    public BoundedHashSet(int bound) {
        this.set = Collections.synchronizedSet(new HashSet<T>());
        this.sem = new Semaphore(bound);
    }

    public boolean add(T o) throws InterruptedException {
        sem.acquire();
        boolean wasAdded = false;
        try {
            wasAdded = set.add(o);
        } finally {
            if (!wasAdded) {
                sem.release();
            }
        }
        return wasAdded;
    }

    public boolean remove(Object o) {
        boolean wasRemoved = set.remove(o);
        if (!wasRemoved) {
            sem.release();
        }
        return wasRemoved;
    }

    public static void main(String[] args) {
        BoundedHashSet boundedHashSet = new BoundedHashSet(5);
        try {
            boundedHashSet.add(1);
            boundedHashSet.add(2);
            boundedHashSet.add(3);
            boundedHashSet.add(4);
            boundedHashSet.add(5);
            //boundedHashSet.add(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
